<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of OrderContronller
 *
 * @author Vu
 */
include APPLICATION_PATH . "/models/Agent.php";
include APPLICATION_PATH . "/models/Area.php";
include APPLICATION_PATH . "/models/Product.php";
include APPLICATION_PATH . "/models/Agent_Product.php";
include APPLICATION_PATH . "/models/Order.php";
include APPLICATION_PATH . "/models/Order_Detail.php";
include APPLICATION_PATH . "/models/Area_Province_Category.php";

class OrderController extends Zend_Controller_Action {

    //put your code here

    public function init() {
        $bootstrap = $this->getInvokeArg("bootstrap");
        $this->aConfig = $bootstrap->getOptions();
        $this->view->aConfig = $this->aConfig;
        $this->Areamodel = new Model_Area();
        $this->AreamodelMapper = new Model_AreaMapper();
        $this->AgentProductmodel = new Model_Agent_Product();
        $this->AgentProductmodelMapper = new Model_Agent_ProductMapper();
        $this->Agentmodel = new Model_Agent();
        $this->AgentmodelMapper = new Model_AgentMapper();
        $this->model = new Model_Order();
        $this->modelMapper = new Model_OrderMapper();
        $this->OrderDeltailmodel = new Model_Order_Detail();
        $this->OrderDeltailmodelMapper = new Model_Order_DetailMapper();
        $this->modelMapperDetail = new Model_Order_DetailMapper();
        $this->AreaProvincemodel = new Model_Area_Province_Category();
        $this->AreaProvincemodelMapper = new Model_Area_Province_CategoryMapper();
        $this->ProductmodelMapper = new Model_ProductMapper();
        $this->user = GlobalLib::getUserLogin();
    }

    public function indexAction() {
        $this->view->provinceHTML = GlobalLib::getComboByProvince('province_id', 'province', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getAgentAndDistrict(\'' . $this->aConfig["site"]["url"] . '\')"');
        $this->view->districtHTML = GlobalLib::getComboByDistrict('district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id=0', '', 'onchange="regetAgentbyProvince(\'' . $this->aConfig["site"]["url"] . '\')"');
        $this->view->agentHTML = GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML = GlobalLib::getComboByProduct('product_id', 'product', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#province_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        //        
        $this->view->popupareaHTML = GlobalLib::getComboByArea('popup_area_id', 'area', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getProvince(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#popup_area_id\').val(),\'popup_province_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupprovinceHTML = GlobalLib::getComboByProvince('popup_province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= 0 )', '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#popup_province_id\').val(),\'popup_district_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->popupdistrictHTML = GlobalLib::getComboByDistrict('popup_district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id= 0');
    }

    public function addorderdetailAction() {
        $id = $this->_getParam("id", "0");
        if ($this->getRequest()->isPost()) {
            $check_exist = FALSE;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items) {
                if ($items->getOrder_Id() == $_POST['order_no']) {
                    if ($items->getProduct_Id() == $_POST['product_id'] &&
                            $items->getAgent_Id() == $_POST['agent_id'] &&
                            GlobalLib::viewDate($items->getOrder_Created()) == $_POST['order_created']) {
                        $check_exist = TRUE;
                        $items->setQuantity($items->getQuantity() + intval($_POST['quantity']));
                        $items->setCharges($items->getCharges() + intval($_POST['charges']));
                        $items->setOrder_Status_Id(intval($_POST['submit_type']));
                        $this->OrderDeltailmodelMapper->save($items);
                    }
                }
            }
            $this->modelMapper->find($id, $this->model);
            if (!$check_exist) {
                $this->OrderDeltailmodel = new Model_Order_Detail();
                $this->OrderDeltailmodel->setOrder_Id($_POST['order_no']);
                $this->OrderDeltailmodel->setProduct_Id($_POST['product_id']);
                $this->OrderDeltailmodel->setQuantity($_POST['quantity']);
                $this->OrderDeltailmodel->setFactor($_POST['factor']);
                $this->OrderDeltailmodel->setCharges($_POST['charges']);
                $this->OrderDeltailmodel->setAgent_Id($_POST['agent_id']);
                $this->OrderDeltailmodel->setOrder_Status_Id(intval($_POST['submit_type']));
                $this->OrderDeltailmodel->setOrder_Created(GlobalLib::toMysqlDateString($_POST['order_created']));
                $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
            }
            // tich diem cho order
            $sum_order_charges = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items) {
                if ($items->getOrder_Id() == $this->model->getOrder_No() && $items->getOrder_Status_Id() == 2) {
                    $sum_order_charges += $items->getCharges();
                    $Order_detail = $items;
                }
            }
            $this->model->setTotal_Charges($sum_order_charges);
            $this->modelMapper->save($this->model);
            // update diem cho store
            $this->AgentmodelMapper->find($this->model->getStore_Id(), $this->Agentmodel);
            $sum_store_charges = 0;
            foreach ($this->modelMapper->fetchAll() as $items) {
                if ($items->getStore_Id() == $this->Agentmodel->getId())
                    $sum_store_charges+= $items->getTotal_Charges();
            }
            $this->Agentmodel->setCharges($sum_store_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);
            // update diem cho agent        
            $this->AgentmodelMapper->find(intval($_POST['agent_id']), $this->Agentmodel);
            $sum_agent_charges = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items) {
                if ($items->getAgent_Id() == $this->Agentmodel->getId() && $items->getOrder_Status_Id() == 2)
                    $sum_agent_charges+= $items->getCharges();
            }
            $this->Agentmodel->setCharges_Sell($sum_agent_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);
            //redirect
            $this->_redirect('/default/order/detail/id/' . $id);
        }
        $this->modelMapper->find($id, $this->model);
        $this->view->item = $this->model;
        $this->view->agentHTML = GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML = GlobalLib::getComboByProduct('product_id', 'product', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#province_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->provinceHTML = GlobalLib::getComboByProvince('province_id', 'province', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getDistrict1(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#province_id\').val(),\'district_id\',\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->districtHTML = GlobalLib::getComboByDistrict('district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id=0', '', 'onchange="getAgent1(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#district_id\').val(),\'agent_id\',\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
    }

    public function addorderAction() {
        $redirectUrl = $this->aConfig["site"]["url"] . "/default/order/index";
        $order_no = GlobalLib::createOrderNo();
        $charges = $this->_getParam("charges", "0");
        $user_id = GlobalLib::getUserLogin();
        $this->AgentmodelMapper->findbyid($user_id['id'], $this->Agentmodel);
        $agent_id = $this->Agentmodel->getId();
        $this->model->setStore_Id($agent_id);
        $this->model->setTotal_Price(0);
        $this->model->setTotal_Charges(0);
        $this->model->setOrder_No($order_no);
        $this->model->setCreated(date("Y/m/d H:i:s"));
        $this->model->setCreated_By(1);
        $this->model->setOrder_Status_Id(1);
        $this->modelMapper->save($this->model);
        echo $order_no;
        exit();
    }

    public function adddetailAction() {
        $order_no = $this->getParam("order_no", "0");
        if ($order_no == "0") {
            $this->_redirect($this->aConfig["site"]["url"] . "/default/order/index");
        }
        $product_id = $this->_getParam("product_id", "0");
        $quantity = $this->_getParam("quantity", "0");
        $agent_id = $this->_getParam("agent_id", "0");
        $factor = $this->_getParam("factor", "0");
        $charges = $this->_getParam("charges", "0");
        $order_created = $this->getParam("order_created", "");
        $this->OrderDeltailmodel->setOrder_Id($order_no);
        $this->OrderDeltailmodel->setProduct_Id($product_id);
        $this->OrderDeltailmodel->setQuantity($quantity);
        $this->OrderDeltailmodel->setAgent_Id($agent_id);
        $this->OrderDeltailmodel->setFactor($factor);
        $this->OrderDeltailmodel->setOrder_Created(GlobalLib::toMysqlDateString($order_created));
        $this->OrderDeltailmodel->setPrice(0);
        $this->OrderDeltailmodel->setCharges($charges);
        $this->OrderDeltailmodel->setOrder_Status_Id(1);
        $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
        echo $order_no;
        exit();
    }

    public function listAction() {
        
    }

    public function editorderdetailAction() {
        $id = $this->_getParam("id", "0");
        $this->OrderDeltailmodelMapper->find($id, $this->OrderDeltailmodel);
        foreach ($this->modelMapper->fetchAll() as $items) {
            if ($this->OrderDeltailmodel->getOrder_Id() == $items->getOrder_No())
                $this->model = $items;
        }
        if ($this->getRequest()->isPost()) {
            $this->OrderDeltailmodelMapper->find($id, $this->OrderDeltailmodel);
            $this->OrderDeltailmodel->setProduct_Id($_POST['product_id']);
            $this->OrderDeltailmodel->setQuantity($_POST['quantity']);
            $this->OrderDeltailmodel->setFactor($_POST['factor']);
            $this->OrderDeltailmodel->setCharges($_POST['charges']);
            $this->OrderDeltailmodel->setAgent_Id($_POST['agent_id']);
            $this->OrderDeltailmodel->setOrder_Status_Id(intval($_POST['submit_type']));
            $this->OrderDeltailmodel->setOrder_Created(GlobalLib::toMysqlDateString($_POST['order_created']));
            $this->OrderDeltailmodelMapper->save($this->OrderDeltailmodel);
            // tich diem cho order
            $sum_order_charges = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items) {
                if ($items->getOrder_Id() == $this->model->getOrder_No() && $items->getOrder_Status_Id() == 2) {
                    $sum_order_charges += $items->getCharges();
                    $Order_detail = $items;
                }
            }
            $this->model->setTotal_Charges($sum_order_charges);
            $this->modelMapper->save($this->model);
            // update diem cho store
            $this->AgentmodelMapper->find($this->model->getStore_Id(), $this->Agentmodel);
            $sum_store_charges = 0;
            foreach ($this->modelMapper->fetchAll() as $items) {
                if ($items->getStore_Id() == $this->Agentmodel->getId())
                    $sum_store_charges+= $items->getTotal_Charges();
            }
            $this->Agentmodel->setCharges($sum_store_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);
            // update diem cho agent        
            $this->AgentmodelMapper->find(intval($_POST['agent_id']), $this->Agentmodel);
            $sum_agent_charges = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items) {
                if ($items->getAgent_Id() == $this->Agentmodel->getId() && $items->getOrder_Status_Id() == 2)
                    $sum_agent_charges+= $items->getCharges();
            }
            $this->Agentmodel->setCharges_Sell($sum_agent_charges);
            $this->AgentmodelMapper->save($this->Agentmodel);
            //redirect
            $this->_redirect('/default/order/detail/id/' . $this->model->getId());
        }

        $this->view->item = $this->model;
        $this->view->item_detail = $this->OrderDeltailmodel;
        $this->view->agentHTML = GlobalLib::getComboByAgent('agent_id', 'agent', 'id', 'name', $this->OrderDeltailmodel->getAgent_Id(), false, 'form-control', '', '', '', 'onchange="getHTML(\'' . $this->aConfig["site"]["url"] . 'kinhdoanh/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#order_created\').val(),\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->productHTML = GlobalLib::getComboByProduct('product_id', 'product', 'id', 'name', $this->OrderDeltailmodel->getProduct_Id(), false, 'form-control', '', '', '', 'onchange="getFactor(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#agent_id\').val(),$(\'#product_id\').val(),$(\'#province_id\').val(),$(\'#order_created\').val(),\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->provinceHTML = GlobalLib::getComboByProvince('province_id', 'province', 'id', 'name', 0, false, 'form-control', '', '', '', 'onchange="getDistrict1(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#province_id\').val(),\'district_id\',\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
        $this->view->districtHTML = GlobalLib::getComboByDistrict('district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id=0', '', 'onchange="getAgent1(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#district_id\').val(),\'agent_id\',\'product_id\',\'factor_id\',\'quantity_id\',\'charges_id\',\'Xin Chờ Trong Giây Lát\');"');
    }

    public function serviceAction() {
        $this->_helper->layout->disableLayout();
        foreach ($this->modelMapper->fetchAll() as $items) {
            $allnew = TRUE;
            //Kiểm tra các chi tiết đều ở tình trạng hủy thì tình trạng đơn hàng là Hủy
            $stt=0;
            $sttCancell = 0;
            foreach ($this->OrderDeltailmodelMapper->fetchAllByOrderNo($items->getOrder_No()) as $detailitem) {               
                if ($items->getOrder_No() == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() > 1) {
                    $allnew = FALSE;                    
                } 
                $stt++;                
                if($items->getOrder_No() == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() == 3){ $sttCancell++; }
                
            }
            
            //var_dump($stt."--".$sttCancell);//exit();
            if (!$allnew && $items->getOrder_Status_Id() == '1')
                $order_status_name = "Đang chờ duyệt";
            else
                $order_status_name = GlobalLib::getName("order_status", $items->getOrder_Status_Id(), "name");
            if( $stt == $sttCancell){ $order_status_name ="Hủy"; }
            $this->AgentmodelMapper->find($items->getStore_Id(), $this->Agentmodel);
            if ($this->Agentmodel->getUser_Id() == $this->user['id']) {
                $menber[] = array(
                    'id' => $items->getId(),
                    'store_name' => GlobalLib::getName('agent', $items->getStore_Id(), 'name'),
                    'order_no' => $items->getOrder_No(),
                    'total_charges' => $items->getTotal_Charges(),
                    'created' => ($items->getCreated()),
                    'order_status' => $order_status_name
                );
            };
        }
        echo json_encode($menber);
        exit();
    }

    public function detailAction() {
        $id = $this->_getParam("id", "0");
        $this->modelMapper->find($id, $this->model);
        $allnew = TRUE;
        foreach ($this->OrderDeltailmodelMapper->fetchAll() as $detailitem) {
            if ($this->model->getOrder_No() == $detailitem->getOrder_Id() && $detailitem->getOrder_Status_Id() > 1) {
                $allnew = FALSE;
                break;
            }
        }
        if (!$allnew && $this->model->getOrder_Status_Id() == '1')
            $order_status_name = "Đang chờ duyệt";
        else
            $order_status_name = GlobalLib::getName("order_status", $this->model->getOrder_Status_Id(), "name");
        $this->view->order_status_name = $order_status_name;
        $this->view->item = $this->model;
    }

    public function servicedetailAction() {
        $this->_helper->layout->disableLayout();
        $order_id = $this->getParam("order_id", "0");
        foreach ($this->OrderDeltailmodelMapper->fetchAll() as $items) {
            if ($order_id == $items->getOrder_Id()) {
                $product_name = "Sản phẩm đã bị xoá!";
                if ($this->ProductmodelMapper->findIn($items->getProduct_Id()) != null)
                    $product_name = GlobalLib::getName('product', $items->getProduct_Id(), 'name');
                $order_status = GlobalLib::getName("order_status", $items->getOrder_Status_Id(), "name");
                $menber[] = array(
                    'id' => $items->getId(),
                    'product_name' => $product_name,
                    'quantity' => $items->getQuantity(),
                    'price' => $items->getPrice(),
                    'factor' => $items->getFactor(),
                    'charges' => $items->getCharges(),
                    'agent_name' => GlobalLib::getName("agent", $items->getAgent_Id(), "name"),
                    'order_created' => $items->getOrder_Created(),
                    'order_status_name' => $order_status,
                    'order_status_id' => $items->getOrder_Status_Id()
                );
            }
        }
        echo json_encode($menber);
        exit();
    }

    public function addagentAction() {
        if ($this->getRequest()->isPost()) {
            $name = $this->_getParam("name", "");
            $address = $this->_getParam("address", "");
            $area_id = $this->_getParam("area_id", "0");
            $province_id = $this->_getParam("province_id", "0");
            $district_id = $this->_getParam("district_id", "0");
            $representavie = $this->_getParam("representavie", "");
            $phone = $this->_getParam("phone", "");
            $agent_cat_id = $this->_getParam("agent_cat_id", "0");
            $agent_status = 1;
            $this->Agentmodel->setCharges(0);
            $this->Agentmodel->setCharges_Sell(0);
            $this->Agentmodel->setName($name);
            $this->Agentmodel->setAddress($address);
            $this->Agentmodel->setArea_Id($area_id);
            $this->Agentmodel->setProvince_Id($province_id);
            $this->Agentmodel->setDistrict_Id($district_id);
            $this->Agentmodel->setRepresentavie($representavie);
            $this->Agentmodel->setPhone($phone);
            $this->Agentmodel->setAgent_Cat_Id($agent_cat_id);
            $this->Agentmodel->setStatus($agent_status);
            $this->Agentmodel->setAgent_Status(1);
            $this->AgentmodelMapper->save($this->Agentmodel);
            echo $this->AgentmodelMapper->getlastid();
            exit();
        }
    }

    public function getareafromprovinceAction() {
        $province_id = $this->_getParam("province_id", "0");
        foreach ($this->AreaProvincemodelMapper->fetchAll() as $items) {
            if ($items->getProvince_Id() == $province_id) {
                echo $items->getArea_Id();
                exit();
            }
        }
        echo 0;
        exit();
    }

    public function getlistprovincefromareaAction() {
        $area_id = $this->_getParam("area_id", "0");
        echo GlobalLib::getComboByProvince('popup_province_id', 'province', 'id', 'name', 0, false, 'form-control', '', 'where id in (select province_id from area_province_category where area_id= ' . $area_id . ")", '', 'onchange="getDistrict(\'' . $this->aConfig["site"]["url"] . 'default/service/index\',$(\'#popup_province_id\').val(),\'popup_district_id\',\'Xin Chờ Trong Giây Lát\');"');
        exit();
    }

    public function getlistdistrictfromprovinceAction() {
        $province_id = $this->_getParam("province_id", "0");
        echo GlobalLib::getComboByDistrict('popup_district_id', 'district', 'id', 'name', 0, false, 'form-control', '', 'where province_id= ' . $province_id);
        exit();
    }

}
